<?php
namespace wogu2\mvc\router\http;

use wogu2\mvc\router\RouterInterface;
use wogu2\stdlib\RequestInterface;

class Common implements RouterInterface
{    
    public function match(RequestInterface $request) {
        $url = $request->getParameter('url', 'get');
        if(!empty($url)) {
            $routerConfig = $this->_runtime->routerConfig;
            
            $pos = strrpos($url, '.');
            $querystring = false !== $pos ? substr($url, 0, $pos) : $url;
            $pos = strpos($querystring, $routerConfig['namespaceActionDelimiter']);
            if(false !== $pos) {
                $namespace = $pos > 0 ? substr($querystring, 0, $pos) : $routerConfig['defaultNamespace'];
                $paramstring = substr($querystring, $pos + 1);
            } else {
                $namespace = $routerConfig['defaultNamespace'];
                $paramstring = $querystring;
            }
            
            $params = explode($routerConfig['parameterDelimiter'], $paramstring);
            $action = !empty($params[0]) ? $params[0] : $routerConfig['defaultAction'];
            
            if(!isset($this->_runtime->actionsMap[$namespace][$action])) {
                $namespace = $routerConfig['defaultErrorNamespace'];
                $action = $routerConfig['defaultErrorAction'];
            }

            $this->_runtime->actionConfig = $this->_runtime->actionsMap[$namespace][$action];
            
            $len = count($params);
            for($i = 1; $i < $len; $i++) {
                if(empty($params[$i])) {
                    ++$i;
                    continue;
                }
    
                $value = isset($params[$i+1]) ?
                        str_replace($routerConfig['parameterDelimiterAlias'], $routerConfig['parameterDelimiter'], $params[$i+1]) : null;
                $this->_runtime->valueStack[$params[$i]] = $value;
                $i++;
            }

            return true;
        }
        
        return false;
    }
}